<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>乒乓球培训管理系统 - 注册</title>
    <!-- Element Plus CSS -->
    <link rel="stylesheet" href="/common/plugins/element-plus/index.css" />
    <!-- Iconify 图标 -->
    <script src="/common/plugins/iconify/iconify-icon.min.js"></script>
    <!-- Tailwind CSS -->
    <script src="/common/plugins/tailwindcss/tailwind.min.js"></script>
    <!-- Vue 3 -->
    <script src="/common/plugins/vue/vue.global.js"></script>
    <!-- Element Plus -->
    <script src="/common/plugins/element-plus/index.full.js"></script>
    <!-- 引入 Axios -->
    <script src="/common/plugins/axios/axios.min.js"></script>
    <!-- 引入 Axios 配置（包含用户API） -->
    <script src="/common/js/axios-config.js"></script>
</head>

<body class="bg-gradient-to-r from-blue-700 to-indigo-800 min-h-screen flex items-center justify-center p-4">
    <div id="app" v-cloak>
        <div class="bg-white rounded-xl shadow-2xl p-8 w-full max-w-lg" style="width: 500px;">
            <div class="text-center mb-8">
                <h1 class="text-2xl font-bold text-gray-800 mb-2">乒乓球培训管理系统</h1>
                <p class="text-gray-600">用户注册</p>
            </div>

            <el-form @submit.prevent="handleRegister" :model="registerForm" :rules="formRules" ref="registerFormRef"
                label-width="100px" label-position="left">

                <!-- 头像上传 -->
                <el-form-item label="头像" prop="avatar">
                    <div class="flex items-center">
                        <div v-if="registerForm.avatar" class="mr-4">
                            <img :src="registerForm.avatar"
                                class="w-16 h-16 rounded-full object-cover border border-gray-200" />
                        </div>
                        <div v-else class="mr-4">
                            <div
                                class="w-16 h-16 rounded-full bg-gray-200 flex items-center justify-center text-gray-500">
                                <iconify-icon icon="mdi:account" width="24" height="24"></iconify-icon>
                            </div>
                        </div>
                        <el-upload class="avatar-uploader" action="/api/file/upload" :show-file-list="false"
                            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :disabled="loading">
                            <el-button type="primary" size="large" :disabled="loading">
                                <iconify-icon icon="mdi:camera" width="16" height="16" class="mr-2"></iconify-icon>
                                选择头像
                            </el-button>
                        </el-upload>
                    </div>
                    <div class="text-sm text-gray-500 mt-1">支持jpg、png格式，文件大小不超过2MB</div>
                </el-form-item>

                <!-- 用户名 -->
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="registerForm.username" placeholder="请输入用户名" :disabled="loading" size="large"
                        clearable maxlength="20" show-word-limit>
                        <template #prefix>
                            <iconify-icon icon="mdi:account" width="16" height="16"
                                class="text-gray-500"></iconify-icon>
                        </template>
                    </el-input>
                </el-form-item>

                <!-- 真实姓名 -->
                <el-form-item label="真实姓名" prop="realName">
                    <el-input v-model="registerForm.realName" placeholder="请输入真实姓名" :disabled="loading" size="large"
                        clearable maxlength="20">
                        <template #prefix>
                            <iconify-icon icon="mdi:account-card-details" width="16" height="16"
                                class="text-gray-500"></iconify-icon>
                        </template>
                    </el-input>
                </el-form-item>

                <!-- 密码 -->
                <el-form-item label="密码" prop="password">
                    <el-input v-model="registerForm.password" type="password" placeholder="请输入密码" :disabled="loading"
                        size="large" show-password clearable maxlength="50">
                        <template #prefix>
                            <iconify-icon icon="mdi:lock" width="16" height="16" class="text-gray-500"></iconify-icon>
                        </template>
                    </el-input>
                </el-form-item>

                <!-- 确认密码 -->
                <el-form-item label="确认密码" prop="confirmPassword">
                    <el-input v-model="registerForm.confirmPassword" type="password" placeholder="请再次输入密码"
                        :disabled="loading" size="large" show-password clearable maxlength="50">
                        <template #prefix>
                            <iconify-icon icon="mdi:lock-check" width="16" height="16"
                                class="text-gray-500"></iconify-icon>
                        </template>
                    </el-input>
                </el-form-item>

                <!-- 性别 -->
                <el-form-item label="性别" prop="gender">
                    <el-select v-model="registerForm.gender" placeholder="请选择性别" :disabled="loading" size="large"
                        style="width: 100%;">
                        <el-option label="男" :value="1">
                            <span class="flex items-center">
                                <iconify-icon icon="mdi:human-male" width="16" height="16"
                                    class="mr-2 text-blue-500"></iconify-icon>
                                男
                            </span>
                        </el-option>
                        <el-option label="女" :value="2">
                            <span class="flex items-center">
                                <iconify-icon icon="mdi:human-female" width="16" height="16"
                                    class="mr-2 text-pink-500"></iconify-icon>
                                女
                            </span>
                        </el-option>
                    </el-select>
                </el-form-item>

                <!-- 年龄 -->
                <el-form-item label="年龄" prop="age">
                    <el-input-number v-model="registerForm.age" placeholder="请输入年龄" :disabled="loading" size="large"
                        :min="5" :max="100" style="width: 100%;">
                    </el-input-number>
                </el-form-item>

                <!-- 手机号 -->
                <el-form-item label="手机号" prop="phone">
                    <el-input v-model="registerForm.phone" placeholder="请输入手机号" :disabled="loading" size="large"
                        clearable maxlength="11" show-word-limit>
                        <template #prefix>
                            <iconify-icon icon="mdi:phone" width="16" height="16" class="text-gray-500"></iconify-icon>
                        </template>
                    </el-input>
                </el-form-item>

                <!-- 邮箱 -->
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="registerForm.email" placeholder="请输入邮箱地址（可选）" :disabled="loading" size="large"
                        clearable maxlength="50">
                        <template #prefix>
                            <iconify-icon icon="mdi:email" width="16" height="16" class="text-gray-500"></iconify-icon>
                        </template>
                    </el-input>
                </el-form-item>

                <!-- 角色选择 -->
                <el-form-item label="角色" prop="userRole">
                    <el-select v-model="registerForm.userRole" placeholder="请选择角色" :disabled="loading" size="large"
                        style="width: 100%;" @change="handleRoleChange">
                        <el-option label="学员" :value="4">
                            <span class="flex items-center">
                                <iconify-icon icon="mdi:school" width="16" height="16"
                                    class="mr-2 text-green-500"></iconify-icon>
                                学员 - 学习乒乓球技能
                            </span>
                        </el-option>
                        <el-option label="教练" :value="3">
                            <span class="flex items-center">
                                <iconify-icon icon="mdi:account-tie" width="16" height="16"
                                    class="mr-2 text-blue-500"></iconify-icon>
                                教练 - 指导学员训练
                            </span>
                        </el-option>
                        <el-option label="校区管理员" :value="2">
                            <span class="flex items-center">
                                <iconify-icon icon="mdi:office-building" width="16" height="16"
                                    class="mr-2 text-orange-500"></iconify-icon>
                                校区管理员 - 管理校区事务
                            </span>
                        </el-option>
                    </el-select>
                </el-form-item>

                <!-- 校区选择（所有角色都需要选择校区） -->
                <el-form-item label="所属校区" prop="campusId" v-if="registerForm.userRole">
                    <el-select v-model="registerForm.campusId" placeholder="请选择所属校区" :disabled="loading" size="large"
                        style="width: 100%;" :loading="loadingCampus">
                        <el-option v-for="campus in campusOptions" :key="campus.id" :label="campus.name"
                            :value="campus.id"></el-option>
                    </el-select>
                </el-form-item>

                <!-- 教练专用字段 -->
                <div v-if="registerForm.userRole === 3">
                    <!-- 教练级别 -->
                    <el-form-item label="教练级别" prop="coachLevel">
                        <el-select v-model="registerForm.coachLevel" placeholder="请选择教练级别" :disabled="loading"
                            size="large" style="width: 100%;">
                            <el-option label="高级教练 (200元/小时)" :value="1">
                                <span class="flex items-center">
                                    <iconify-icon icon="mdi:star" width="16" height="16"
                                        class="mr-2 text-yellow-500"></iconify-icon>
                                    高级教练 (200元/小时)
                                </span>
                            </el-option>
                            <el-option label="中级教练 (150元/小时)" :value="2">
                                <span class="flex items-center">
                                    <iconify-icon icon="mdi:star-half-full" width="16" height="16"
                                        class="mr-2 text-blue-500"></iconify-icon>
                                    中级教练 (150元/小时)
                                </span>
                            </el-option>
                            <el-option label="初级教练 (80元/小时)" :value="3">
                                <span class="flex items-center">
                                    <iconify-icon icon="mdi:star-outline" width="16" height="16"
                                        class="mr-2 text-green-500"></iconify-icon>
                                    初级教练 (80元/小时)
                                </span>
                            </el-option>
                        </el-select>
                    </el-form-item>

                    <!-- 过往成绩 -->
                    <el-form-item label="过往成绩" prop="achievements">
                        <el-input v-model="registerForm.achievements" type="textarea" :rows="3"
                            placeholder="请简要介绍您的过往比赛成绩和执教经历" :disabled="loading" maxlength="500" show-word-limit>
                        </el-input>
                    </el-form-item>
                </div>

                <!-- 学员专用字段 -->
                <div v-if="registerForm.userRole === 4">
                    <!-- 初始余额 -->
                    <el-form-item label="初始余额" prop="balance">
                        <el-input-number v-model="registerForm.balance" placeholder="请输入初始余额" :disabled="loading"
                            size="large" :min="0" :precision="2" style="width: 100%;">
                            <template #prepend>￥</template>
                        </el-input-number>
                        <div class="text-sm text-gray-500 mt-1">注册后可以充值，用于支付课程费用</div>
                    </el-form-item>
                </div>

                <!-- 用户协议 -->
                <el-form-item prop="agreeToTerms">
                    <el-checkbox v-model="registerForm.agreeToTerms" :disabled="loading">
                        我已阅读并同意 <a href="#" class="text-blue-600 hover:text-blue-800"
                            @click.prevent="showTerms">《用户服务协议》</a>
                    </el-checkbox>
                </el-form-item>

                <!-- 注册按钮 -->
                <el-form-item>
                    <el-button type="primary" @click="handleRegister" :loading="loading" size="large" class="w-full">
                        <iconify-icon icon="mdi:account-plus" width="16" height="16" class="mr-2"></iconify-icon>
                        注册
                    </el-button>
                </el-form-item>
            </el-form>

            <!-- 登录链接 -->
            <div class="text-center mt-6">
                <p class="text-gray-600 text-sm">
                    已有账户？
                    <a href="/management-system/login.html" class="text-blue-600 hover:text-blue-800 font-medium">
                        立即登录
                    </a>
                </p>
            </div>

            <div class="mt-8 text-center">
                <p class="text-gray-500 text-sm">&copy; 2025 乒乓球培训管理系统. 保留所有权利.</p>
            </div>
        </div>

        <!-- 用户协议对话框 -->
        <el-dialog title="用户服务协议" v-model="termsDialogVisible" width="600px">
            <div class="space-y-4 max-h-96 overflow-y-auto">
                <h3 class="text-lg font-semibold">欢迎使用乒乓球培训管理系统</h3>
                <p class="text-gray-700 leading-relaxed">
                    在使用本系统前，请仔细阅读以下条款：
                </p>
                <div class="space-y-3 text-sm text-gray-600">
                    <p><strong>1. 服务说明</strong></p>
                    <p>本系统为乒乓球培训学员提供课程预约、教练选择、学习记录等服务。</p>

                    <p><strong>2. 用户责任</strong></p>
                    <p>用户应提供真实、准确的个人信息，妥善保管账户密码，对账户下的所有活动负责。</p>

                    <p><strong>3. 隐私保护</strong></p>
                    <p>我们承诺保护用户隐私，不会泄露用户个人信息给第三方。</p>

                    <p><strong>4. 服务变更</strong></p>
                    <p>我们保留随时修改或终止服务的权利，重要变更将提前通知用户。</p>
                </div>
            </div>
            <template #footer>
                <el-button @click="termsDialogVisible = false">我已了解</el-button>
            </template>
        </el-dialog>
    </div>

    <script>
        const { createApp } = Vue;

        const app = createApp({
            data() {
                // 自定义验证规则
                const validateConfirmPassword = (rule, value, callback) => {
                    if (value === '') {
                        callback(new Error('请再次输入密码'));
                    } else if (value !== this.registerForm.password) {
                        callback(new Error('两次输入密码不一致'));
                    } else {
                        callback();
                    }
                };

                const validatePhone = (rule, value, callback) => {
                    if (value === '') {
                        callback(new Error('请输入手机号'));
                    } else if (!/^1[3-9]\d{9}$/.test(value)) {
                        callback(new Error('请输入正确的手机号'));
                    } else {
                        callback();
                    }
                };

                const validateEmail = (rule, value, callback) => {
                    if (value && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) {
                        callback(new Error('请输入正确的邮箱格式'));
                    } else {
                        callback();
                    }
                };

                const validateAgreeToTerms = (rule, value, callback) => {
                    if (!value) {
                        callback(new Error('请同意用户服务协议'));
                    } else {
                        callback();
                    }
                };

                return {
                    registerForm: {
                        avatar: '',
                        username: '',
                        password: '',
                        confirmPassword: '',
                        realName: '',
                        gender: undefined,
                        age: undefined,
                        phone: '',
                        email: '',
                        userRole: 4, // 默认为学员
                        campusId: undefined,
                        coachLevel: undefined,
                        achievements: '',
                        balance: 0,
                        agreeToTerms: false
                    },
                    // 校区选项和加载状态
                    campusOptions: [],
                    loadingCampus: false,
                    formRules: {
                        username: [
                            { required: true, message: '请输入用户名', trigger: 'blur' },
                            { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' },
                            { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', trigger: 'blur' }
                        ],
                        password: [
                            { required: true, message: '请输入密码', trigger: 'blur' },
                            { min: 6, max: 50, message: '密码长度在 6 到 50 个字符', trigger: 'blur' }
                        ],
                        confirmPassword: [
                            { validator: validateConfirmPassword, trigger: 'blur' }
                        ],
                        realName: [
                            { required: true, message: '请输入真实姓名', trigger: 'blur' },
                            { min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' }
                        ],
                        gender: [
                            { required: true, message: '请选择性别', trigger: 'change' }
                        ],
                        age: [
                            { required: true, message: '请输入年龄', trigger: 'blur' },
                            { type: 'number', min: 5, max: 100, message: '年龄必须在 5 到 100 之间', trigger: 'blur' }
                        ],
                        phone: [
                            { validator: validatePhone, trigger: 'blur' }
                        ],
                        email: [
                            { validator: validateEmail, trigger: 'blur' }
                        ],
                        agreeToTerms: [
                            { validator: validateAgreeToTerms, trigger: 'change' }
                        ],
                        userRole: [
                            { required: true, message: '请选择角色', trigger: 'change' }
                        ],
                        campusId: [
                            { required: true, message: '请选择所属校区', trigger: 'change' }
                        ],
                        coachLevel: [
                            {
                                validator: (rule, value, callback) => {
                                    if (this.registerForm.userRole === 3 && !value) {
                                        callback(new Error('请选择教练级别'));
                                    } else {
                                        callback();
                                    }
                                },
                                trigger: 'change'
                            }
                        ],
                        achievements: [
                            {
                                validator: (rule, value, callback) => {
                                    if (this.registerForm.userRole === 3 && (!value || value.trim() === '')) {
                                        callback(new Error('请填写过往成绩'));
                                    } else {
                                        callback();
                                    }
                                },
                                trigger: 'blur'
                            }
                        ],
                        balance: [
                            {
                                validator: (rule, value, callback) => {
                                    if (this.registerForm.userRole === 4 && (value === null || value === undefined || value < 0)) {
                                        callback(new Error('初始余额不能为负数'));
                                    } else {
                                        callback();
                                    }
                                },
                                trigger: 'blur'
                            }
                        ]
                    },
                    loading: false,
                    termsDialogVisible: false
                };
            },
            methods: {
                // 注册处理函数
                async handleRegister() {
                    try {
                        // 表单验证
                        const valid = await this.$refs.registerFormRef.validate();
                        if (!valid) return;

                        this.loading = true;

                        console.log('开始注册:', this.registerForm.username);

                        // 创建注册数据对象
                        const registerData = {
                            avatar: this.registerForm.avatar || null,
                            username: this.registerForm.username,
                            password: this.registerForm.password,
                            realName: this.registerForm.realName,
                            gender: this.registerForm.gender,
                            age: this.registerForm.age,
                            phone: this.registerForm.phone,
                            email: this.registerForm.email || null,
                            userRole: this.registerForm.userRole,
                            campusId: this.registerForm.campusId
                        };

                        // 根据角色添加专用字段
                        if (this.registerForm.userRole === 3) { // 教练
                            registerData.coachLevel = this.registerForm.coachLevel;
                            registerData.achievements = this.registerForm.achievements;
                        } else if (this.registerForm.userRole === 4) { // 学员
                            registerData.balance = this.registerForm.balance;
                        }

                        // 调用增强后的注册接口（已在后端配置为不需要token，支持多角色）
                        const result = await apiClient.post('/users/register', registerData);

                        console.log('注册响应:', result);

                        if (result.code === 200) {
                            this.$message.success('注册成功！请使用您的账户登录。');

                            // 延迟跳转到登录页面
                            setTimeout(() => {
                                window.location.href = '/management-system/login.html';
                            }, 1500);
                        }
                        // axios拦截器已经处理了错误情况，这里不需要再处理

                    } catch (error) {
                        console.error('注册失败:', error);
                        // 注册失败后清空密码字段
                        this.registerForm.password = '';
                        this.registerForm.confirmPassword = '';
                    } finally {
                        this.loading = false;
                    }
                },

                // 显示用户协议
                showTerms() {
                    this.termsDialogVisible = true;
                },

                // 头像上传前的验证
                beforeAvatarUpload(file) {
                    const isImage = file.type.startsWith('image/');
                    const isLt2M = file.size / 1024 / 1024 < 2;

                    if (!isImage) {
                        this.$message.error('头像必须是图片格式!');
                        return false;
                    }
                    if (!isLt2M) {
                        this.$message.error('头像大小不能超过 2MB!');
                        return false;
                    }
                    return true;
                },

                // 头像上传成功的处理
                handleAvatarSuccess(response) {
                    if (response.code === 200) {
                        this.registerForm.avatar = response.data.fileUrl;
                        this.$message.success('头像上传成功');
                    } else {
                        this.$message.error(response.message || '头像上传失败');
                    }
                },

                // 角色变化处理
                handleRoleChange(role) {
                    // 清空角色相关的字段
                    this.registerForm.coachLevel = undefined;
                    this.registerForm.achievements = '';
                    this.registerForm.balance = 0;

                    // 根据角色设置默认值
                    if (role === 3) { // 教练
                        this.registerForm.coachLevel = 3; // 默认初级教练
                    } else if (role === 4) { // 学员
                        this.registerForm.balance = 0; // 默认余额为0
                    }
                },

                // 创建不需要token的axios实例
                createNoTokenClient() {
                    const noTokenClient = axios.create({
                        baseURL: '/api',
                        timeout: 30000,
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    });

                    // 添加响应拦截器处理统一的响应格式
                    noTokenClient.interceptors.response.use(
                        function (response) {
                            const data = response.data;
                            // 检查业务状态码
                            if (data && typeof data.code !== 'undefined') {
                                if (data.code === 200) {
                                    return data;
                                } else {
                                    // 业务错误
                                    ElementPlus.ElMessage.error(data.message || '操作失败');
                                    return Promise.reject(new Error(data.message));
                                }
                            }
                            return data;
                        },
                        function (error) {
                            console.error('请求失败:', error);
                            let errorMessage = '网络错误，请稍后重试';
                            if (error.response) {
                                errorMessage = `服务器错误 (${error.response.status})`;
                            } else if (error.request) {
                                errorMessage = '网络连接失败';
                            }
                            ElementPlus.ElMessage.error(errorMessage);
                            return Promise.reject(error);
                        }
                    );

                    return noTokenClient;
                },

                // 加载校区选项
                async loadCampusOptions() {
                    this.loadingCampus = true;
                    try {
                        const noTokenClient = this.createNoTokenClient();
                        const response = await noTokenClient.get('/campus/all');
                        if (response.code === 200) {
                            this.campusOptions = response.data || [];
                        } else {
                            this.$message.error('获取校区列表失败');
                        }
                    } catch (error) {
                        console.error('获取校区列表失败:', error);
                        this.$message.error('获取校区列表失败');
                    } finally {
                        this.loadingCampus = false;
                    }
                }
            },
            async mounted() {
                console.log('注册页面Vue应用已挂载');

                // 检查是否已经登录
                if (isLoggedIn()) {
                    console.log('用户已登录，跳转到主页');
                    window.location.href = '/management-system/index.html';
                    return;
                }

                // 加载校区选项
                await this.loadCampusOptions();
            }
        });

        // 使用 Element Plus
        app.use(ElementPlus);

        // 挂载应用
        app.mount('#app');

        console.log('🚀 注册页面 Vue 应用已启动');
    </script>

    <style>
        [v-cloak] {
            display: none;
        }

        /* 自定义滚动条样式 */
        .el-dialog__body {
            padding: 20px;
        }

        /* 确保输入框在小屏幕上也能正常显示 */
        @media (max-width: 640px) {
            .el-row .el-col {
                margin-bottom: 16px;
            }
        }
    </style>
</body>

</html>